package net.wenku8.reader.api.wkt

import android.util.Log
import com.alibaba.fastjson2.JSON
import net.wenku8.reader.entity.ApiResult
import net.wenku8.reader.state.StateLogin
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody

class WktApi {


    companion object {

        private const val URL = "http://wkt.bitkit.cn/transfer"

        fun request(param : Map<String, String>) : ApiResult<String> {
            val params = param + ("sid" to StateLogin.Companion.sessionId.value) + ("source" to "bitkit")
            val reqBuilder = Request.Builder().url(URL)
            val reqBody = RequestBody.Companion.create("application/json".toMediaTypeOrNull(), JSON.toJSONString(params));
            reqBuilder.post(reqBody)
            val clientBuilder = OkHttpClient.Builder()
            clientBuilder.hostnameVerifier { _, _ -> true }
            val resp = clientBuilder.build().newCall(reqBuilder.build()).execute()
            if (resp.code != 200){
                Log.i("ApiConnect request resp.code", resp.code.toString())
                return ApiResult.Companion.fail("中转服务器请求失败:"+resp.code)
            }
            val respBody = resp.body?: return ApiResult.Companion.fail("中转服务器返回数据为空")
            val jsonObj = JSON.parseObject(respBody.string())
            if(jsonObj.getIntValue("code", 1001) == 1000){
                return ApiResult.Companion.success(jsonObj.getString("data"))
            }
            return ApiResult.Companion.fail(jsonObj.getString("msg"))

        }


    }
}